/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author duanzuocai
 * @since 2018/10/22
 */
layui.define(['form', 'layedit', 'xmSelect', 'zmnBind', 'zmnSelect'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var xmSelect = layui.xmSelect;
    var zmnBind = layui.zmnBind;
    let zmnSelect = layui.zmnSelect;
    form.render(null, "zmn-form");
    // 自定义验证规则
    form.verify({
        positiveOrZero: function(value){
            if(value){
                if (!/^0$|^[1-9][0-9]*$/.test(value)) {
                    return "请输入正整数或者0";
                }
            }
        },
        positive: function(value){
            if(value){
                if (!/^[1-9][0-9]*$/.test(value)) {
                    return "请输入大于0的正整数";
                }
            }
        }
    });

    // 初始化联动
    zmnTrack.laySelectSpecial(form, "/orderconfig/track/lisComplain.action", "/orderconfig/track/lisComplain.action", "complainOneId", "complainTwoId", "complainContentId");
    zmnTrack.laySelectSpecial(form, "/orderconfig/track/listAbnor.action", "/orderconfig/track/listAbnor.action", "abnorOneId", "abnorTwoId", "abnorContentId");



    // 联动多选
    let trackDeptId = json.trackDeptId?json.trackDeptId.split(','):[];
    let orderStatus = json.orderStatus?json.orderStatus.split(','):[];
    let trackReason = json.trackReason?json.trackReason.split(','):[];
    let trackId = json.trackId?json.trackId:'';
    let selectMapDept = zmnSelect.select({
        trackDeptId: {
                sizeModel: "small", //尺寸模式：medium；small；mini
                showCount: 0, //选择值展示个数
                page: { //分配配置
                    enable: true,  //开关：true-开启；false-关闭
                    pageSize: 50,   //页数
                },
                // searchedValue: null, //已搜索值（用于回显）
                selectedValues: trackDeptId, //已选中值（用于回显)
                remote: { //远程获取下拉数据
                    enable: true, //开关：true-开启；false-关闭
                    url: "/orderconfig/track/listDept.action", //服务url
                }
        }
    });

    let selectMapOrderStatus = zmnSelect.select({
        orderStatus: {
            sizeModel: "small", //尺寸模式：medium；small；mini
            showCount: 0, //选择值展示个数
            page: { //分配配置
                enable: true,  //开关：true-开启；false-关闭
                pageSize: 50,   //页数
            },
            // searchedValue: null, //已搜索值（用于回显）
            selectedValues: orderStatus, //已选中值（用于回显)
            remote: { //远程获取下拉数据
                enable: true, //开关：true-开启；false-关闭
                url: "/orderconfig/track/listOrderStatus.action", //服务url
            }
        }
    });

    let selectMapTrackReason = zmnSelect.select({
        trackReason: {
            sizeModel: "small", //尺寸模式：medium；small；mini
            showCount: 0, //选择值展示个数
            page: { //分配配置
                enable: true,  //开关：true-开启；false-关闭
                pageSize: 50,   //页数
            },
            // searchedValue: null, //已搜索值（用于回显）
            selectedValues: trackReason, //已选中值（用于回显)
            remote: { //远程获取下拉数据
                enable: true, //开关：true-开启；false-关闭
                url: "/orderconfig/trackReason/listVt.action?trackId="+trackId, //服务url
            }
        }
    });

    let  trackDeptSelect = selectMapDept["trackDeptId"];
    let  orderStatusSelect = selectMapOrderStatus["orderStatus"];
    let  trackReasonSelect = selectMapTrackReason["trackReason"];

    // // 二级缘由新增
    // //添加分组
    // $('form').delegate(".addReason","click",function () {
    //     //分组最多添加10个，多余10个给出提示
    //     let groupLegnth = $('form input[name="levelTwoReason"]').length;
    //     if(groupLegnth>=10){
    //         return layer.msg("分组最多添加10个",{time: 1000});
    //     }
    //     // 组
    //     let current= $(this).parents('div.reasons');
    //     //新的组
    //     let newDiv = $('<div class="layui-form-item reasons"></div>');
    //     newDiv.html($('#copyDiv').html());
    //     newDiv.insertAfter(current);
    //     form.render();
    // });


    // 提交
    form.on('submit(zmn-form-submit)', function(obj){
        // let params = {};
        let data = obj.field;
        let deptIds = trackDeptSelect.getValue();
        let orderStatus = orderStatusSelect.getValue();
        let trackReasons = trackReasonSelect.getValue();
        // let levelTwoReasonInput = layui.$('form input[name="levelTwoReason"]');
        // if(levelTwoReasonInput.length>10){
        //     layer.msg("二级缘由最多只能10个")
        //     return false;
        // }
        if(!data.level){
            layer.msg("跟单等级不能为空")
            return false;
        }
        if(!data.legacy){
            layer.msg("是否遗留不能为空")
            return false;
        }
        if(deptIds.length<1){
            layer.msg("跟单部门不能为空");
            return false;
        }
        if(orderStatus.length<1){
            layer.msg("订单状态不能为空");
            return false;
        }
        if(trackReasons.length<1||trackReasons.length>10){
            layer.msg("跟单缘由不能为空且不能超过十个");
            return false;
        }
        if(!data.billType){
            layer.msg("单据类型不能为空");
            return false;
        }
        if(!data.trackOperator){
            layer.msg("发起人不能为空");
            return false;
        }
        if(!data.bizType){
            layer.msg("业务类型不能为空")
            return false;
        }

        // let levelTwoReason= [];
        // levelTwoReasonInput.each(function (index,item) {
        //     let current = $(item);
        //     let reason = current.val();
        //     let reasonId = current.next("input").val();
        //     let status= current.parent().next(":checkbox:checked").length>0?2:1;
        //     levelTwoReason.push({"reasonId":reasonId?reasonId:'',"reason":reason,"status":status});
        // });

        //特殊字段重新赋值
        // 二级缘由
        // params.levelTwoReason = levelTwoReason;
        // params.orderTrack = data;
        // params.trackId = data.trackId;
        // 部门和订单状态
        let trackDeptId = [];
        let trackOrderStatus = [];
        let trackReasonIds = [];
        deptIds.forEach((i)=>{
            trackDeptId.push(i.value);
        });
        orderStatus.forEach((i)=>{
            trackOrderStatus.push(i.value);
        });
        trackReasons.forEach((i)=>{
            trackReasonIds.push(i.value);
        });
        data.trackDeptId=trackDeptId.join(",");
        data.orderStatus=trackOrderStatus.join(",");
        data.trackReason=trackReasonIds.join(",");
        //单据类型多选赋值
        let billTypes = [];
        layui.$('form input[name="billType"]:checked').each((index,item)=>{
            billTypes.push($(item).val());
        });
        data.billType=billTypes.join(",");
        // 发起人
        let trackOperators = [];
        layui.$('form input[name="trackOperator"]:checked').each((index,item)=>{
            trackOperators.push($(item).val());
        });
        data.trackOperator=trackOperators.join(",");
        // 业务类型
        let bizTypes = [];
        layui.$('form input[name="bizType"]:checked').each((index,item)=>{
            bizTypes.push($(item).val());
        });
        data.bizType=bizTypes.join(",");
        console.log(JSON.stringify(data));

        $.ajax({
            type: "POST", url: "/orderconfig/track/addEdit.action",
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (data) {
                if (data.status == 200) {
                    layer.msg("操作成功", {time: 1000}, function () {
                        location.reload();
                    });
                } else {
                    layer.msg(data.message, {"icon": 2});
                }
            }
        });
        return false;
    });

    layui.$("#cancleBtn").click(function () {
        let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index); //再执行关闭
        return false;
    });
    //对外暴露的接口
    exports('track_detail_js', {});
});


var zmnTrack = {
    /**
     * 多级下拉框联动
     * @param form layui.form
     * @param url1 selectOneId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param url1 selectTwoId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param selectOneId 第1级select的ID，不含#号
     * @param selectTwoId 第2级select的ID，不含#号
     * @param selectThrId 第3级select的ID，不含#号，如无第3级则两级联动
     */
    laySelectSpecial: function (form, url1, url2, selectOneId, selectTwoId, selectThrId) {
        let $ = layui.$;
        let oneLevelId;
        let twoLevelId;
        let html = '<option value="">选择</option>';
        form.on("select(" + selectOneId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0||!obj.value) {
                $("#"+selectTwoId).html(html);
                $("#"+selectThrId).html(html);
                form.render("select");
                return;
            }
            oneLevelId = obj.value;
            $.ajax({
                type: "GET", url: url1,
                dataType: "json", data: {oneLevelId: oneLevelId},
                success: function (json) {
                    let items = json.data;
                    var optionHtml = '<option value="">选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i].value + '">' + items[i].text + '</option>';
                    }
                    $("#" + selectTwoId).html(optionHtml);
                    form.render("select");
                }
            });
        });
        if (zmnUtil.isEmptyNull(selectThrId)) {
            form.render("select");
            return;
        }
        ;

        form.on("select(" + selectTwoId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0||!obj.value) {
                $("#"+selectThrId).html(html);
                form.render("select");
                return;
            }
            twoLevelId = obj.value;
            oneLevelId = $('#'+selectOneId).val();
            $.ajax({
                type: "GET", url: url2,
                dataType: "json", data: {twoLevelId: obj.value, oneLevelId: oneLevelId},
                success: function (json) {
                    let items = json.data;
                    var optionHtml = '<option value="">选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i].value + '">' + items[i].text + '</option>';
                    }
                    $("#" + selectThrId).html(optionHtml);
                    form.render("select");
                }
            });
        });
    },
}
